const puppeteer = require('puppeteer');
const config = require('./config');
const src2img = require('./helper/src2img');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://image.baidu.com/');

  await page.setViewport({
    width: 1920,
    height: 1080
  });

  const keyword = '暴漫表情包';

  try {
    await page.focus('#kw');
    await page.keyboard.sendCharacter(keyword);
    await page.click('.s_btn');
  } catch (error) {
    console.log(error);
  }
  console.log('go search keyword --> ' + keyword);

  page.on('load', async ()=>{
    console.log('fetch after loading the page ...');
    const srcs = await page.evaluate(() => {
      const images = document.querySelectorAll('img.main_img');
      return Array.prototype.map.call(images, img => img.src);
    });

    src.forEach((src, mn) => {
      src2img(src,mn);
    });
  })
})();
